<?php

class AdminModule extends CWebModule
{
	private $_assetsUrl;
	private $clientScript;
	
	public function init()
	{
		// this method is called when the module is being created
		// you may place code here to customize the module or the application

		// import the module-level models and components
		$this->setImport(array(
			'admin.models.*',
			'admin.components.*',
		));
		
		
		
		$this->clientScript = Yii::app()->getClientScript();
     	$this->clientScript->registerCoreScript('assets');
     	
     	
     	$returnUrl =  Yii::app()->createUrl('/site/login', array('referer'=>UtilTools::curPageURL()));
     	
     	if(Yii::app()->user->isGuest) header("location:".$returnUrl);
	}
	
	/**
	 * @return string the base Url that conntains all publised asset files
	 * @see CWebModule::beforeControllerAction()
	 */
	public function getAssetsUrl()
	{
		if($this->_assetsUrl == null)
		{	
			$dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'assets';
   			$this->_assetsUrl = Yii::app()->getAssetManager()->publish($dir);
			
		}
		return $this->_assetsUrl;
	}
	
	/**
	 * @param string the base Url that container all the published asset files
	 *
	 */
	public function setAssetsUrl($value)
	{
		$this->_assetsUrl = $value;
	}
	
	public function registerScript($file,$postion=CClientScript::POS_BEGIN)
	{
		if(is_array($file)){
			foreach ($file as $script){
				$this->clientScript->registerScriptFile($this->_assetsUrl.'/js/'.$script,$postion);  
			}
		}else {
			$this->clientScript->registerScriptFile($this->_assetsUrl.'/js/'.$file,$postion);  
		}
			
	}
	
	public function registerCss($file,$media = 'all')
	{
		if(is_array($file)){
			foreach ($file as $item){
				$href = $this->getAssetsUrl().'/css/'.$item;
				$this->clientScript->registerCssFile($this->_assetsUrl.'/css/'.$file);		
				
			}
		}else{
			$href = $this->getAssetsUrl().'/css/'.$file;
			$this->clientScript->registerCssFile($this->_assetsUrl.'/css/'.$file);
		}
	}
	
	public function registerImage($file)
	{
		return $this->getAssetsUrl().'/images/'.$file;
	}
	
	public function beforeControllerAction($controller, $action)
	{
		if(parent::beforeControllerAction($controller, $action))
		{
			// this method is called before any module controller action is performed
			// you may place customized code here
			return true;
		}
		else
			return false;
	}
}
